package com.njxzc.demo.service.before;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.njxzc.demo.common.MD5Util;
import com.njxzc.demo.common.http.ResponseResult;
import com.njxzc.demo.common.security.utils.ConfigrarionBean;
import com.njxzc.demo.common.security.utils.JwtTokenUtil;
import com.njxzc.demo.common.security.utils.RedisUtil;
import com.njxzc.demo.entity.BUserEntity;
import com.njxzc.demo.mapper.before.BUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class BUserServiceImpl extends ServiceImpl<BUserMapper, BUserEntity> implements BUserService{

    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private ConfigrarionBean config;

    @Override
    public ResponseResult<Map<String, String>> register(BUserEntity bUserEntity) {
        //1。密码md5加密
        bUserEntity.setBpwd(MD5Util.MD5(bUserEntity.getBpwd()));

        //2。查询邮箱是否已注册
        long res= lambdaQuery().eq(BUserEntity::getBemail, bUserEntity.getBemail()).count();

        if(res > 0 ) {//邮箱已注册，数据库中有数据
            return ResponseResult.getMessageResult(null, "A001");
        } else if(save(bUserEntity)) {//未注册，则将数据保存至数据库中
            return ResponseResult.getMessageResult(null, "A002");
        } else {//注册失败
            return ResponseResult.getMessageResult(null, "A003");
        }
    }

    @Override
    public ResponseResult<Map<String, String>> login(BUserEntity bUserEntity) {
        //1.验证码核实
        String validCode = (String) redisUtil.get("code");
        if(!validCode.equalsIgnoreCase(bUserEntity.getCode())){
            return ResponseResult.getMessageResult(null, "A002");
        }
        //2.判断用户名是否存在
        long res = lambdaQuery().eq(BUserEntity::getBemail, bUserEntity.getBemail()).count();
        if(res == 0){
            //用户名不存在
            return ResponseResult.getMessageResult(null, "A002");
        }

        Map<String, String> map = new HashMap<>();
        map.put("bemail", bUserEntity.getBemail());
        map.put("bpwd", MD5Util.MD5(bUserEntity.getBpwd()));
        List<BUserEntity> mu = query().allEq(map).list();

        if(mu.size() > 0){
            String token = jwtTokenUtil.createToken(bUserEntity.getBemail());
            redisUtil.set("login_"+bUserEntity.getBemail(), bUserEntity.getBemail(), config.getRedisExpiration());
            Map<String, String> myres = new HashMap<>();
            myres.put("authtoken", token);
            myres.put("bemail", bUserEntity.getBemail());
//            myres.put("bpwd", bUserEntity.getBpwd()); 密码不可返回到前端
            myres.put("bid", mu.get(0).getId() + "");
            return ResponseResult.getSuccessResult(myres);
        }else{
            /* 密码错误 */
            return ResponseResult.getMessageResult(null, "A002");
        }
    }
}
